// src/routes/index.tsx
import React, { lazy, Suspense, FC } from "react";
import { useRoutes } from "react-router-dom";
import { HomeOutlined, ShopOutlined, SettingOutlined } from "@ant-design/icons";

import type { XRoutes } from "./types";
import { useAppSelector } from "@/app/hooks";

import {
  Layout,
  EmptyLayout,
  // CompLayout
} from "../layouts";
import Loading from "@comps/Loading";
import Redirect from "@comps/Redirect";

const Login = lazy(() => import("@pages/login"));
const Dashboard = lazy(() => import("@pages/dashboard"));
const NotFound = lazy(() => import("@pages/404"));
const Trademark = lazy(() => import("@comps/Product/Trademark")); // 品牌管理
const User = lazy(() => import("@comps/Acl/User")); // 用户管理

const load = (Comp: FC) => {
  return (
    // 因为路由懒加载，组件需要一段网络请求时间才能加载并渲染
    // 在组件还未渲染时，fallback就生效，来渲染一个加载进度条效果
    // 当组件渲染完成时，fallback就失效了
    <Suspense fallback={<Loading />}>
      {/* 所有lazy的组件必须包裹Suspense组件，才能实现功能 */}
      <Comp />
    </Suspense>
  );
};

const routes: XRoutes = [
  {
    path: "/",
    element: <EmptyLayout />,
    children: [
      {
        path: "login",
        element: load(Login),
      },
    ],
  },
  {
    path: "/syt",
    element: <Layout />,
    meta: { name: "Syt" },
    children: [
      {
        path: "/syt/dashboard",
        meta: { icon: <HomeOutlined />, title: "首页" },
        element: load(Dashboard),
      },
      // {
      //   path: "/syt/acl",
      //   element: <EmptyLayout />,
      //   meta: { icon: <SettingOutlined />, title: "权限管理", name: "Acl" },
      //   children: [
      //     {
      //       path: "/syt/acl/user/list",
      //       meta: { title: "用户管理", name: "User" },
      //       element: load(User),
      //     },
      //   ],
      // },
      // {
      //   path: "/syt/product",
      //   element: <EmptyLayout />,
      //   meta: { icon: <ShopOutlined />, title: "商品管理", name: "Product" },
      //   children: [
      //     {
      //       path: "/syt/product/trademark",
      //       meta: { title: "品牌管理", name: "Trademark" },
      //       element: load(Trademark),
      //     },
      //   ],
      // },
    ],
  },

  {
    path: "/404",
    element: load(NotFound),
  },
  {
    path: "*",
    element: <Redirect to="/404" />,
  },
];

// 动态路由
const asyncRoutes = [
  {
    path: "/syt/acl",
    element: <EmptyLayout />,
    meta: { icon: <SettingOutlined />, title: "权限管理", name: "Acl" },
    children: [
      {
        path: "/syt/acl/user/list",
        meta: { title: "用户管理", name: "User" },
        element: load(User),
      },
    ],
  },
  {
    path: "/syt/product",
    element: <EmptyLayout />,
    meta: { icon: <ShopOutlined />, title: "商品管理", name: "Acl" },
    children: [
      {
        path: "/syt/product/trademark",
        meta: { title: "品牌管理", name: "Trademark" },
        element: load(Trademark),
      },
    ],
  },
];

// 过滤路由
const dynamicRoutes = (asyncRoutes: any, routes: any) => {
  return asyncRoutes.filter((route: any) => {
    if (!routes.includes((route.meta || {}).name)) return false;
    if (route.children && route.children.length > 0) {
      route.children = dynamicRoutes(route.children, routes);
    }
    return true;
  });
};

// 递归拷贝
function deepClone(obj: any) {
  if (typeof obj !== "object" || obj == null) {
    return obj;
  }
  let result: any = obj instanceof Array ? [] : {};
  for (let attr in obj) {
    result[attr] = deepClone(obj[attr]);
  }
  return result;
}

// 渲染路由
// 注意：首字母必须大写
export const RenderRoutes = () => {
  // react-router-dom的新增语法。不用自己遍历了，它帮我们遍历生成
  let newRoutes: any = [];
  const routesName = useAppSelector((state) => state.user.routes);
  const showRoutes = [...dynamicRoutes(asyncRoutes, routesName)];
  routes.forEach((item) => {
    if (item.path === "/syt") {
      newRoutes = Array.from(new Set(item.children));
      showRoutes.forEach((route) => {
        item.children?.forEach((value) => {
          if (route.meta.name !== value.meta?.name) {
            item.children?.push(route);
          }
        });
      });
    }
  });

  if(newRoutes.length > 1){
    routes[1].children = newRoutes 
  }

  return useRoutes(routes);
};

// 找到要渲染成左侧菜单的路由
export const findSideBarRoutes = () => {
  const currentIndex = routes.findIndex((route) => route.path === "/syt");
  return routes[currentIndex].children as XRoutes;
};

export default routes;
